import Empty from '@/components/Empty';
import { getDeviceCascader } from '@/utils/formatterTree';
import { SearchOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Input, Spin, Tree } from 'antd';
import React, { useEffect, useState } from 'react';
import Styles from './CommonStyles.less';

type IProps = {
  changeNodes: (data: any) => void;
};

// 假设的设备树数据类型
interface Device {
  deviceName: string;
  uniqueId: string;
  subDevices?: Device[];
}

// 树数据
const DeviceTree: React.FC<IProps> = (props) => {
  const intl = useIntl();
  const [spinning, setSpinning] = useState(false);
  const { changeNodes } = props;
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [deviceTreeData, setDeviceTreeData] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchValue(value);
    const newExpandedKeys: string[] = [];
    const filterTree = (data: Device[]) => {
      return data
        .map((item) => {
          const isMatch = item.deviceName.toLowerCase().includes(value.toLowerCase());
          if (isMatch) {
            newExpandedKeys.push(item.uniqueId);
          }
          if (item.subDevices) {
            const filteredChildren = filterTree(item.subDevices);
            if (filteredChildren.length > 0) {
              newExpandedKeys.push(item.uniqueId);
              return { ...item, subDevices: filteredChildren };
            }
          }
          return isMatch ? item : null;
        })
        .filter(Boolean) as Device[];
    };
    filterTree(deviceTreeData);
    setExpandedKeys(value ? newExpandedKeys : []);
  };

  const getDeviceTree = () => {
    setSpinning(true);
    getDeviceCascader(true)
      .then((res) => {
        setDeviceTreeData(res);
        setSpinning(false);
      })
      .catch(() => {
        setSpinning(false);
      });
  };
  const treeFilter = (data: Device[]) => {
    return data
      .map((item) => {
        if (item.subDevices) {
          const filteredChildren = treeFilter(item.subDevices);
          if (filteredChildren.length > 0) {
            return { ...item, subDevices: filteredChildren };
          }
        }
        const deviceName = item.deviceName || '';
        return deviceName.toLowerCase().includes(searchValue.toLowerCase()) ||
          (item.subDevices && item.subDevices.length > 0)
          ? item
          : null;
      })
      .filter(Boolean) as Device[];
  };
  const filterTreeData = treeFilter(deviceTreeData);
  useEffect(() => {
    getDeviceTree();
  }, []);
  return (
    <>
      <div className={Styles.left}>
        <Spin spinning={spinning}>
          {deviceTreeData.length === 0 ? (
            <Empty></Empty>
          ) : (
            <div>
              <div>
                <Input
                  style={{ marginBottom: 8 }}
                  value={searchValue}
                  placeholder={intl.formatMessage({ id: 'hisCurve.enterPlaceholder' })}
                  addonAfter={<SearchOutlined />}
                  onChange={handleSearch}
                ></Input>
              </div>
              <div className={Styles.leftTree}>
                <Tree
                  onExpand={(newExpandKeys) => {
                    setExpandedKeys(newExpandKeys);
                    setAutoExpandParent(false);
                  }}
                  expandedKeys={expandedKeys}
                  autoExpandParent={autoExpandParent}
                  treeData={filterTreeData}
                  fieldNames={{
                    title: 'deviceName',
                    key: 'uniqueId',
                    children: 'subDevices',
                  }}
                  onSelect={(selectedKeys: string[], e) => {
                    changeNodes(e.node);
                  }}
                ></Tree>
              </div>
            </div>
          )}
        </Spin>
      </div>
    </>
  );
};
export default DeviceTree;
